#include "MainWindow.h"
#include <QDebug>

Mapviewer::Mapviewer(QWidget *parent)
    : QMainWindow(parent)
{
    // create MapControl
    mc = new MapControl(QSize(380, 540));
    mc->showScale(true);

    // create mapadapter, for mainlayer and overlay
    mapadapter = new OSMMapAdapter();

    // create a layer with the mapadapter and type MapLayer
    mainlayer = new MapLayer("OpenStreetMap-Layer", mapadapter);

    // add Layer to the MapControl
    mc->addLayer(mainlayer);

    // create and start roter
    router = new OSRMRouter();
    connect(router, SIGNAL(routingFinished(int)), this, SLOT(drawRoute(int)));
    router->findRoute(QPointF(30.24330,50.42223), QPointF(30.5, 50.583333));

    addZoomButtons();

    // show mapcontrol in mainwindow
    setCentralWidget(mc);

    // sets the view to the interesting area
    mc->setView(QPointF(30.52333, 50.45));

    mc->setZoom(11);

    // set cashe folder
    ImageManager::instance()->setCacheDir(QDir("/home/green/Diploma/MapCache"));
}


void Mapviewer::addZoomButtons()
{
    // create buttons as controls for zoom
    QPushButton* zoomin = new QPushButton("+");
    QPushButton* zoomout = new QPushButton("-");
    zoomin->setMaximumWidth(50);
    zoomout->setMaximumWidth(50);

    connect(zoomin, SIGNAL(clicked(bool)),
            mc, SLOT(zoomIn()));
    connect(zoomout, SIGNAL(clicked(bool)),
            mc, SLOT(zoomOut()));

    // add zoom buttons to the layout of the MapControl
    QVBoxLayout* innerlayout = new QVBoxLayout;
    innerlayout->addWidget(zoomin);
    innerlayout->addWidget(zoomout);
    mc->setLayout(innerlayout);
}


Mapviewer::~Mapviewer()
{
}

// resize the widget
void Mapviewer::resizeEvent ( QResizeEvent * event )
{
    mc->resize(event->size());
}

void Mapviewer::drawRoute(int error)
{
    if(error != OSRMRouter::NO_ERROR)
        return;

    QList<Point*> points;
    QListIterator<QPointF> it(router->currentRouteRef());
    QPointF tmpPoint;
    while(it.hasNext())
    {
        tmpPoint = it.next();
        points.append(new Point(tmpPoint.x(), tmpPoint.y()));
    }

    // A QPen also can use transparency
    QPen* linepen = new QPen(QColor(0, 255, 0));
    linepen->setWidth(5);

    LineString* ls = new LineString(points, "GGG", linepen);

    mainlayer->addGeometry(ls);
}
